package com.swordget.dao.impl;

import com.swordget.commons.JdbcUtil;
import com.swordget.dao.TemplateManagerDao;
import com.swordget.entity.TemplateDesign;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

/**
 * @Author: David
 * @Date: Created in 15:07 2020/5/12
 * @Description: 模板管理 Dao 实现
 * @Modified By:
 * @Version:
 */
@Repository
public class TemplateManagerDaoImp implements TemplateManagerDao {

    @Autowired
    private JdbcUtil jdbcUtil;


    @Override
    public boolean save(TemplateDesign newTemplate) {
        String command = String.format("INSERT INTO TEMPLATE(SERIALNO, NAME, TABLEID, TABLENAME, TEMPLATETYPE, ISDEFAULT, TEMPLATECONT, FILEID, CREATEUSER, CREATEDATE, CREATETIME) " +
                "VALUES('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s')", newTemplate.getSerialNo(), newTemplate.getName(),
                newTemplate.getTableId(), newTemplate.getTableName(), newTemplate.getTemplateType(), newTemplate.getIsDefault(),
                newTemplate.getTemplateCont(), newTemplate.getFileId(), newTemplate.getCreateUser(), newTemplate.getCreateDate(),
                newTemplate.getCreateTime());
        return jdbcUtil.execute(command);
    }

    @Override
    public boolean remove(String serialNo) {
        String command  = String.format("DELETE FROM TEMPLATE WHERE SERIALNO = '%s'", serialNo);
        return jdbcUtil.execute(command);
    }

    @Override
    public int count(String tableId, String name) {
        String command = String.format("SELECT COUNT(*) FROM TEMPLATE WHERE TABLEID = '%s' AND NAME = '%s'", tableId, name);
        return jdbcUtil.executeCount(command);
    }

    /**
     * 设置默认模板
     * @param serialNo 默认模板只能同时有一个 所以两个语句必须是事务的
     * @param type 模板类型
     * @return
     */
    @Override
    public boolean setDefault(String serialNo, String type) {

        String command = String.format("UPDATE TEMPLATE SET ISDEFAULT = 'Y' WHERE SERIALNO = '%s' AND TEMPLATETYPE = '%s'",
                serialNo, type);
        String commandEl = String.format("UPDATE TEMPLATE SET ISDEFAULT = 'N' WHERE SERIALNO <> '%s' AND TEMPLATETYPE = '%s' ",
                serialNo, type);
        return jdbcUtil.executeBatch(command, commandEl);
    }

    @Override
    public String findTemplateJson(String template) {
        String command = String.format("SELECT TEMPLATECONT FROM TEMPLATE WHERE SERIALNO = '%s'", template);
        return (String) jdbcUtil.findOne(command);
    }

    @Override
    public int countByType(String tableId, String templateType) {
        String command = String.format("SELECT COUNT(*) FROM TEMPLATE WHERE TABLEID = '%s' AND TEMPLATETYPE = '%s'", tableId, templateType);
        return jdbcUtil.executeCount(command);
    }
}
